package com.mobile.challenge.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.king.base.util.SharedPreferencesUtils;
import com.mobile.challenge.R;
import com.mobile.challenge.bean.DataBean;
import com.mobile.challenge.bean.TrackingBean;
import com.mobile.challenge.databinding.FragmentHomeBinding;
import com.mobile.challenge.ui.DashboardActivity;
import com.mobile.challenge.ui.SeatChooseActivity;
import com.mobile.challenge.user.UserHelper;
import com.mobile.challenge.util.DateUtil;
import com.mobile.challenge.widget.ArcSeekBar;
import com.mobile.frame.mvvmframe.base.BaseFragment;
import com.othershe.calendarview.bean.DateBean;
import com.othershe.calendarview.listener.OnPagerChangeListener;
import com.othershe.calendarview.listener.OnSingleChooseListener;
import com.othershe.calendarview.weiget.CalendarView;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import static android.app.Activity.RESULT_OK;
import static com.mobile.challenge.util.ConstantsKt.IN_OFFICE;
import static com.mobile.challenge.util.ConstantsKt.VACATION;
import static com.mobile.challenge.util.ConstantsKt.WFH;


public class HomeFragment extends BaseFragment<HomeViewModel, FragmentHomeBinding> {

    public static String currentStatus = "";

    private TextView mProgressText;
    private TextView mTxtDate;
    private ArcSeekBar mArcSeekBar;
    private ImageView mImageMood;
    private ImageView mImageBg;

    private Calendar mCalendar = Calendar.getInstance();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mProgressText = mBinding.getRoot().findViewById(R.id.txt_progress);
        mArcSeekBar = mBinding.getRoot().findViewById(R.id.arc_seek_bar);
        mImageMood = mBinding.getRoot().findViewById(R.id.image_mood);
        mImageBg = mBinding.getRoot().findViewById(R.id.image_text_bg);
        mTxtDate = mBinding.getRoot().findViewById(R.id.txt_date);

        mArcSeekBar.setMaxValue(99);
        mArcSeekBar.setMinValue(0);
        setWorkLocation(mArcSeekBar.getProgress());
        DataBean dataBean = ((DashboardActivity) getActivity()).getDataBean();
        if (dataBean != null) {
            mBinding.tvName.setText("Hello " + dataBean.getUser().getName());
        }

        if (UserHelper.Companion.getInstance().hasSignIn()) {
            mBinding.constraintLayout.setVisibility(View.VISIBLE);
            mBinding.btResult.setText(UserHelper.Companion.getInstance().getLocation(UserHelper.Companion.getInstance().getTrackingStatus()));
            requestSignInStatus();
            mBinding.layoutTracking.setVisibility(View.GONE);
        } else {
            showSignInView();
        }

        mImageBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mProgressText.getText().toString().equals(IN_OFFICE)) {
                    Intent intent = new Intent(requireActivity(), SeatChooseActivity.class);
//                    requireActivity().startActivityForResult();
                    startActivityForResult(intent, 200, null);
                } else {
                    showLoading();
                    signIn();
                }
            }
        });

        mBinding.tvEditNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSignInView();
            }
        });

        mArcSeekBar.setOnProgressChangeListener(new ArcSeekBar.OnProgressChangeListener() {
            @Override
            public void onProgressChanged(ArcSeekBar seekBar, int progress, boolean isUser) {
                setWorkLocation(seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(ArcSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(ArcSeekBar seekBar) {
                setWorkLocation(seekBar.getProgress());
            }
        });

        mTxtDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCalendarDialog();
            }
        });

        mViewModel.getSignInData().observe(getViewLifecycleOwner(), trackingBean -> {
            hideLoading();
            mBinding.constraintLayout.setVisibility(View.VISIBLE);
            mBinding.btResult.setText(UserHelper.Companion.getInstance().getLocation(trackingBean.getStatus()));
            requestSignInStatus();
            mBinding.layoutTracking.setVisibility(View.GONE);
            saveStatus(currentStatus);
        });

        mViewModel.getSignInError().observe(getViewLifecycleOwner(), e -> {
            hideLoading();
            Toast.makeText(requireContext(), "sign in error, please try it again after a few minutes.", Toast.LENGTH_SHORT)
                    .show();
        });

        mBinding.calendarView.setOnDateChangeListener(new android.widget.CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull android.widget.CalendarView view, int year, int month, int dayOfMonth) {
                mCalendar.set(Calendar.YEAR, year);
                mCalendar.set(Calendar.MONTH, month);
                mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                requestSignInStatus();
            }
        });

        mViewModel.getSignInStatus().observe(getViewLifecycleOwner(), status ->
                mBinding.btResult.setText(UserHelper.Companion.getInstance().getLocation(status))
        );

        requestSignInStatus();

    }

    private void showSignInView() {
        mBinding.constraintLayout.setVisibility(View.GONE);
        mBinding.layoutTracking.setVisibility(View.VISIBLE);
        TrackingBean tracking = mViewModel.getTracking();
        if (tracking != null) {
            switch (tracking.getStatus()) {
                case 1:
                    mArcSeekBar.setProgress(50);
                    break;
                case 2:
                    mArcSeekBar.setProgress(100);
                    break;
                case 3:
                    mArcSeekBar.setProgress(0);
                    break;
                default:
                    break;
            }
        }
    }

    private void requestSignInStatus() {
        mViewModel.requestSignInStatus(mCalendar);
    }

    private void signIn() {
        mViewModel.updateSignIn(
                String.valueOf(UserHelper.Companion.getInstance().getUserId()),
                String.valueOf(UserHelper.Companion.getInstance().getLocationStatus(currentStatus)),
                DateUtil.getFormatDateStr(mCalendar)
        );
    }

    public void saveStatus(String status) {
        SharedPreferencesUtils.put(requireContext(), "STATUS", status);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 200) {
                if (data != null) {
                    int seatid = data.getIntExtra("seatid", 0);

                    showLoading();
                    signIn();
                }
            }
        }
    }

    private void setWorkLocation(int progress) {
        if (progress <= 33) {
            mProgressText.setText(VACATION);
            currentStatus = VACATION;
            mImageMood.setImageResource(R.drawable.smiley_super_happy);
        } else if (progress > 33 && progress < 66) {
            mProgressText.setText(IN_OFFICE);
            mImageMood.setImageResource(R.drawable.smiley_disappointed);
            currentStatus = IN_OFFICE;
        } else {
            mProgressText.setText(WFH);
            mImageMood.setImageResource(R.drawable.smiley_happy);
            currentStatus = WFH;
        }

    }

    private void showCalendarDialog() {
        BottomSheetDialog calendarSheet = new BottomSheetDialog(requireActivity(), R.style.Theme_Design_BottomSheetDialog);
        calendarSheet.setCancelable(true);
        calendarSheet.setContentView(R.layout.dialog_calendar);
        CalendarView calendarView = calendarSheet.findViewById(R.id.calendar);
        TextView textDate = calendarSheet.findViewById(R.id.text_choose_date);
//日历init，年月日之间用点号隔开
        calendarView
                .setStartEndDate("2020.9", "2020.9")
                .setInitDate("2020.9")
                .setSingleDate("2020.9.18")
                .init();
//月份切换回调
        calendarView.setOnPagerChangeListener(new OnPagerChangeListener() {
            @Override
            public void onPagerChanged(int[] date) {

            }
        });

        calendarView.setOnSingleChooseListener(new OnSingleChooseListener() {
            @Override
            public void onSingleChoose(View view, DateBean date) {
                int[] solar = date.getSolar();
                int year = solar[0];
                int month = solar[1];
                int day = solar[2];
                textDate.setText(getEngMonth(month) + " " + day + "," + year);
                mTxtDate.setText(getEngMonth(month) + " " + day + "," + year);
            }
        });
        calendarSheet.show();
    }

    private String getEngMonth(int month) {
        String engMon = "Sep";
        switch (month) {
            case 1:
                engMon = "Jan";
                break;
            case 2:
                engMon = "Feb";
                break;
            case 3:
                engMon = "Mar";
                break;
            case 4:
                engMon = "Apr";
                break;
            case 5:
                engMon = "May";
                break;
            case 6:
                engMon = "Jun";
                break;
            case 7:
                engMon = "Jul";
                break;
            case 8:
                engMon = "Aug";
                break;
            case 9:
                engMon = "Sep";
                break;
            case 10:
                engMon = "Oct";
                break;
            case 11:
                engMon = "Nov";
                break;
            case 12:
                engMon = "Dec";
                break;
        }
        return engMon;
    }
}

